package com.itboye.ihomebank.activity.keytwo;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.itboye.ihomebank.R;
import com.itboye.ihomebank.adapter.MainAdapter;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.SystemMessBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreater;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yanzhenjie.recyclerview.swipe.SwipeItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

public class KeyActivity extends BaseOtherActivity implements Observer, SwipeItemClickListener {
    protected SwipeMenuRecyclerView recycler_view;
    protected MainAdapter mAdapter;

    private UserPresenter userPresenter;
    List<SystemMessBean.Sysitem> list;
    private int pageNo = 1;
    private SmartRefreshLayout refresh;

    @Override
    protected int layout_id() {
        return R.layout.activity_key;
    }

    @Override
    protected void onInitController() {
    }

    @Override
    protected void onInit() {
        list = new ArrayList<>();
        userPresenter = new UserPresenter(this);

        refresh = (SmartRefreshLayout) findViewById(R.id.refresh);
        refresh.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）

        mAdapter = new MainAdapter(this);
        recycler_view.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged(list);

        recycler_view.setSwipeItemClickListener(this);//点击事件
        recycler_view.setSwipeMenuCreator(swipeMenuCreator);//菜单创建
        recycler_view.setSwipeMenuItemClickListener(mMenuItemClickListener);//RecyclerView的Item的Menu点击监听

        recycler_view.setLayoutManager(new LinearLayoutManager(this));//设置布局格式
        //设置Item增加、移除动画
        recycler_view.setItemAnimator(new DefaultItemAnimator());
        //添加分割线
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        dividerItemDecoration.setDrawable(getResources().getDrawable(R.drawable.shape_lins));
        recycler_view.addItemDecoration(dividerItemDecoration);

//        //触发自动刷新
        refresh.autoRefresh();
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        pageNo = 1;
                        userPresenter.getSystemMess("359", 3 + "", pageNo + "", "10");
                    }
                }, 0);
            }
        });

        //进行加载更多的逻辑处理
        refresh.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        pageNo++;
                        userPresenter.getSystemMess("359", 3 + "", pageNo + "", "10");
                    }
                }, 0);
            }
        });

        //设置头布局样式,全局有效
        refresh.setDefaultRefreshHeaderCreater(new DefaultRefreshHeaderCreater() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                //全局设置主题颜色
                layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
                //指定为经典Header，默认是 贝塞尔雷达Header
                return new ClassicsHeader(context).setSpinnerStyle(SpinnerStyle.Translate);
            }
        });
        //设置脚布局样式,全局有效
        refresh.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setSpinnerStyle(SpinnerStyle.Translate);
            }
        });
        refresh.setRefreshHeader(new MaterialHeader(this).setShowBezierWave(true));
        //  refresh.setRefreshFooter(new BallPulseFooter(this).setSpinnerStyle(SpinnerStyle.Scale));
        refresh.finishLoadmore();
    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    @Override
    public void onClick(View v) {

    }

    /**
     * 菜单创建器，在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            int width = getResources().getDimensionPixelSize(R.dimen.DIMEN_70DP);

            // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
            // 2. 指定具体的高，比如80;
            // 3. WRAP_CONTENT，自身高度，不推荐;
            int height = ViewGroup.LayoutParams.MATCH_PARENT;
            // 添加右侧的，如果不添加，则右侧不会出现菜单。
            {
                SwipeMenuItem  addItem = new SwipeMenuItem(KeyActivity.this)
                        .setBackground(R.drawable.selector_green)
                        .setText("删除")
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height);
                swipeRightMenu.addMenuItem(addItem); // 添加菜单到右侧。
            }
        }
    };
    boolean delete = false;//用来标记是删除还是确定删除
    int tag=-1;//用来标记是不是还是点击的同一个位置
    /**
     * RecyclerView的Item的Menu点击监听。
     */
    private SwipeMenuItemClickListener mMenuItemClickListener = new SwipeMenuItemClickListener() {
        @Override
        public void onItemClick(SwipeMenuBridge menuBridge) {
            int adapterPosition = menuBridge.getAdapterPosition(); // RecyclerView的Item的position。
            if (tag!=adapterPosition){
                menuBridge.setText("确认删除");
                delete = false;
                tag=adapterPosition;
            }else{
                menuBridge.setText("删除");
                delete = true;
                tag=-1;
            }
            if (delete){//确定删除
                menuBridge.closeMenu();
               Toast.makeText(KeyActivity.this, "确定删除", Toast.LENGTH_SHORT).show();
            }else{//删除
               Toast.makeText(KeyActivity.this, "删除", Toast.LENGTH_SHORT).show();
            }

        }
    };

    @Override
    public void update(Observable o, Object arg) {
        ResultEntity entity = handlerError(arg);
        if (entity != null) {
            if (!entity.getCode().equals(0)) {
                if (entity.getEventType() == UserPresenter.sysMess_success) {
                    SystemMessBean bean = (SystemMessBean) entity.getData();
                    ByAlert.alert(bean);
                    // list.addAll(bean.getList());
                    list = bean.getList();
                    if (pageNo == 1) {//下拉刷新
                        mAdapter.refresh(list);
                        //结束加载
                        refresh.finishRefresh();
                    } else {//上拉加载
                        mAdapter.loadmore(list);
                        //结束加载
                        refresh.finishLoadmore();
                    }
                }
                if (entity.getEventType() == UserPresenter.sysMess_fail) {
                    ByAlert.alert(entity.getMsg());
                    refresh.finishLoadmore();
                    refresh.finishRefresh();
                }
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
    }

    @Override
    public void onItemClick(View view, int i) {
        ByAlert.alert(i + "");
    }
}
